﻿using System;
using System.Web.Services.Protocols;
using System.IO;

namespace FJ.JiraAnalysis.JiraRPCv3
{
    public class JiraSoapExtensions : SoapExtension
    {
        private Stream m_inwardStream;
        private Stream m_outwardStream;

        public override void ProcessMessage(SoapMessage message)
        {
            string _soapMsg;
            StreamReader _readStr;
            StreamWriter _writeStr;

            switch (message.Stage)
            {
                case SoapMessageStage.BeforeSerialize:
                    break;
                case SoapMessageStage.AfterDeserialize:
                    break;
                case SoapMessageStage.BeforeDeserialize:
                    _readStr = new StreamReader(m_outwardStream);
                    _writeStr = new StreamWriter(m_inwardStream);
                    _soapMsg = _readStr.ReadToEnd();

                    if (message.MethodInfo.Name == "getWorklogs")
                    {
                        _soapMsg = _soapMsg.Replace("IssueServiceImpl$RemoteWorklogImpl", "IssueServiceImplRemoteWorklogImpl");
                    }

                    _writeStr.Write(_soapMsg);
                    _writeStr.Flush();
                    m_inwardStream.Position = 0;
                    break;
                case SoapMessageStage.AfterSerialize:
                    m_inwardStream.Position = 0;
                    _readStr = new StreamReader(m_inwardStream);
                    _writeStr = new StreamWriter(m_outwardStream);
                    _soapMsg = _readStr.ReadToEnd();

                    _writeStr.Write(_soapMsg);
                    _writeStr.Flush();
                    break;
            }
        }

        public override Stream ChainStream(Stream stream)
        {
            m_outwardStream = stream;
            m_inwardStream = new MemoryStream();
            return m_inwardStream;
        }

        public override object GetInitializer(Type type)
        {
            return GetType();
        }

        public override object GetInitializer(LogicalMethodInfo info, SoapExtensionAttribute attribute)
        {
            return null;
        }

        public override void Initialize(object initializer)
        {
        }
    }
}
